﻿using System.Buffers;
using SuperSocket.ProtoBase;

namespace SS.PipelineFilter.Server;


public class MyPackage : IKeyedPackageInfo<short> {
    public short Key { get; set; }
    public byte[] Body { get; set; }
}


///
/// 协议: 头部包含 6 个字节, 前 4 个字节用于存储请求的名字, 后两个字节用于代表请求体的长度:
/// +-------+-----+-------------------------------+
/// | name  | len |      request body             |
/// |  (4)  | (2) |                               |
/// +-------+-----+-------------------------------+
public class MyPipelineFilter () : FixedHeaderPipelineFilter<MyPackage>(headerSize: HeaderSize) {
    private const int HeaderSize = 4; //Header总长度

    private const int HeaderLenOffset = 2; //长度offset

    //包头大小是4字节，所以将4传入基类构造方法

    //从数据包的头部返回包体的大小
    protected override int GetBodyLengthFromHeader(ref ReadOnlySequence<byte> buffer)
    {
        var reader = new SequenceReader<byte>(buffer);
        reader.Advance(HeaderLenOffset); //跳过前2个字节
        reader.TryReadBigEndian(out short len); //以大端方式读取short类型数据
        return len;
    }

    protected override MyPackage DecodePackage(ref ReadOnlySequence<byte> buffer)
    {
        var reader = new SequenceReader<byte>(buffer);
        reader.TryReadBigEndian(out short packageKey);

        var body = buffer.Slice(HeaderSize).ToArray();
        return new MyPackage
        {
            Key = packageKey,
            Body = body
        };
    }
}